package com.hwbsite.hwbback.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hwbsite.hwbback.consstants.CacheConstants;
import com.hwbsite.hwbback.entity.HwbUser;
import com.hwbsite.hwbback.entity.RoleInfo;
import com.hwbsite.hwbback.entity.UserInfo;
//import com.hwbsite.hwbback.mapper.UserMapper;
import com.hwbsite.hwbback.mapper.PermissionInfoMapper;
import com.hwbsite.hwbback.mapper.RoleInfoMapper;
import com.hwbsite.hwbback.mapper.UserInfoMapper;
import lombok.AllArgsConstructor;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserInfoMapper userMapper;
    private final RoleInfoMapper roleInfoMapper;
    private final PermissionInfoMapper permissionInfoMapper;
    private final RedisTemplate redisTemplate15;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        String user = (String) redisTemplate15.opsForValue().get(CacheConstants.USER_DETAILS + name);
        UserInfo userInfo = null;
        if (StrUtil.isNotBlank(user)) {

            userInfo =  JSONUtil.toBean( user, UserInfo.class);
        }else {
         userInfo = userMapper.selectOne(Wrappers.lambdaQuery(UserInfo.class).eq(UserInfo::getUsername, name).eq(UserInfo::getIsValid, true));
        }
        if(userInfo == null){
            throw  new UsernameNotFoundException("未找到用户名【" + name + "】请先注册" );
        }

        UserDetails userDetails = getUserDetails(userInfo);


        redisTemplate15.opsForValue().set(CacheConstants.USER_DETAILS + name, JSONUtil.toJsonStr(userInfo));

        return userDetails;
    }

    private UserDetails  getUserDetails(UserInfo userInfo){
        Set<String> dbAuthsSet = new HashSet<>();

//        if (ArrayUtil.isNotEmpty(userInfo.getRolesId())) {
//            // 获取角色
//            Arrays.stream(userInfo.getRolesId().split(";")).forEach(role ->
//                    {
//                        List<RoleInfo> roles =  roleInfoMapper.selectList(Wrappers.<RoleInfo>lambdaQuery().eq(RoleInfo::getRoleId, role));
//
//                        roles.forEach(per->{
//                            dbAuthsSet.add(permissionInfoMapper.selectById(per.getPermissionId()).getPermissionName());
//                        });
//                    });
//
//        }
        Collection<? extends GrantedAuthority>  authorities = AuthorityUtils
                .createAuthorityList(dbAuthsSet.toArray(new String[0]));
        return new HwbUser(userInfo.getUsername() , userInfo.getPassword(), authorities, userInfo);
    }

}
